package com.mall.shopping.services;

import com.mall.shopping.IHomeService;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.PanelDto;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;

/**
 * @DATE: 28/9/2021  21:40
 * @USER: xiaom
 * @Author: 2232683886@qq.com
 * @Description: 显示主页
 */
@Slf4j
@Component
@Service
public class HomeServiceImpl implements IHomeService {

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ContentConverter contentConverter;

    /**
     * 主页显示接口
     * @return HomePageResponse
     */
    @Override
    public HomePageResponse homepage() {

        HomePageResponse homePageResponse = new HomePageResponse();

        getHomePageResponse(homePageResponse);

        return homePageResponse;
    }

    private void getHomePageResponse(HomePageResponse homePageResponse) {
        try {

            // 首先查出所有的panel
            List<Panel> panels = panelMapper.selectAll();

            // 封装panel -> panelDto
            HashSet<PanelDto> panelContentItemDtos = new HashSet<>();


            // 通过遍历panels查询对应所有的panelContent
            for (Panel panel : panels) {

                // panel -> panelDto
                PanelDto panelDto = contentConverter.panen2Dto(panel);

                List<PanelContentItem> panelContentItems
                        = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());

                // panelContentItems -> panelContentItems
                panelDto.setPanelContentItems(contentConverter.panelContentItem2Dto(panelContentItems));

                // 封装进Set中
                panelContentItemDtos.add(panelDto);

            }

            homePageResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            homePageResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            homePageResponse.setPanelContentItemDtos(panelContentItemDtos);

        } catch (Exception e) {

            log.error("HomeServiceImpl.homepage occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(homePageResponse,e);

        }
    }
}
